package com.xx.sg.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xx.sg.excel.DutyExcel;
import com.xx.sg.exception.ServiceException;
import com.xx.sg.own.entity.Duty;
import com.xx.sg.own.entity.DutyDeptArea;
import com.xx.sg.own.entity.User;
import com.xx.sg.own.service.DutyDeptAreaService;
import com.xx.sg.own.service.DutyService;
import com.xx.sg.own.service.UserService;
import com.xx.sg.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/duty")
@Tag(name = "值班Api", description = "值班Api")
public class DutyController {

    @Autowired
    private DutyService dutyService;
    @Autowired
    private DutyDeptAreaService dutyDeptAreaService;
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @Operation(summary = "值班列表查询", description = "值班列表查询")
    public R list(@ModelAttribute Duty duty) {
        List<Duty> list = dutyService.selectDutyList(duty);
        return R.success(list);
    }

    @GetMapping("/info")
    @Operation(summary = "值班信息查询", description = "值班信息查询")
    public R info(String id) {
        Duty duty = dutyService.selectDutyById(id);
        return R.success(duty);
    }

    @PostMapping("/save")
    @Operation(summary = "添加值班信息", description = "添加值班信息")
    public R save(@RequestBody Duty duty) {
        if (StringUtils.isNotBlank(duty.getId())) {
            dutyService.modifyDuty(duty);
        } else {
            dutyService.saveDuty(duty);
        }

        return R.success();
    }

    @PostMapping("/modify")
    @Operation(summary = "修改值班信息", description = "修改值班信息")
    public R modify(@RequestBody Duty duty) {
        dutyService.modifyDuty(duty);
        return R.success();
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除值班信息", description = "删除值班信息")
    public R delete(@PathVariable("id") String id) {
        LambdaUpdateWrapper<Duty> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Duty::getId, id)
                .set(Duty::getDeleteFlag, 1);
        dutyService.update(wrapper);
        return R.success();
    }

    @PostMapping("/import")
    @Operation(summary = "值班信息导入", description = "值班信息导入")
    public R importExcel(@RequestParam("file") MultipartFile file,
                         @RequestParam(name = "date", required = false) LocalDate date) {
        if (file == null) {
            throw new ServiceException("上传文件信息为null");
        }

        if (date == null) {
            date = LocalDate.now();
        }
        List<DutyExcel> dutyExcelList = new ArrayList<>();
        try {
            EasyExcel.read(file.getInputStream(), new AnalysisEventListener<Map<Integer, String>>() {
                        @Override
                        public void invoke(Map<Integer, String> data, AnalysisContext context) {
                            String unitName = data.get(0);
                            String directorName = data.get(8);
                            String leaderName = data.get(9);
                            String staffName = data.get(10);
                            if (StringUtils.isNotBlank(staffName)) {
                                DutyExcel dutyExcel = DutyExcel.builder()
                                        .unitName(unitName.replaceAll("[\\s\\u3000\\u00A0]+", ""))
                                        .directorName(directorName)
                                        .leaderName(leaderName)
                                        .staffName(staffName)
                                        .build();
                                dutyExcelList.add(dutyExcel);
                            }
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext context) {
                        }
                    })
                    .sheet()
                    .headRowNumber(4)
                    .doRead();


            List<String> userList = new ArrayList<>();
            List<String> deptList = new ArrayList<>();
            List<DutyDeptArea> configList = dutyDeptAreaService.list();
            Map<String, String> configMap = configList.stream().collect(Collectors.toMap(DutyDeptArea::getAreaName, DutyDeptArea::getDeptId));
            for (DutyExcel dutyExcel : dutyExcelList) {
                List<User> staffUsers = userService.selectUserByName(dutyExcel.getStaffName());
                List<User> leaderUsers = userService.selectUserByName(dutyExcel.getLeaderName());
                List<User> directorUsers = userService.selectUserByName(dutyExcel.getDirectorName());

                if (staffUsers.isEmpty()) {
                    userList.add(dutyExcel.getStaffName());
                    deptList.add(dutyExcel.getUnitName());
                    continue;
                    //throw new ServiceException(dutyExcel.getStaffName() + "不存在,导入失败");
                }

                if (leaderUsers.isEmpty()) {
                    userList.add(dutyExcel.getLeaderName());
                    deptList.add(dutyExcel.getUnitName());
                    continue;
                    //throw new ServiceException(dutyExcel.getLeaderName() + "不存在,导入失败");
                }

                if (directorUsers.isEmpty()) {
                    userList.add(dutyExcel.getDirectorName());
                    deptList.add(dutyExcel.getUnitName());
                    continue;
                    //throw new ServiceException(dutyExcel.getDirectorName() + "不存在,导入失败");
                }

                Duty duty = Duty.builder()
                        .dutyDate(date)
                        .deptId(configMap.get(dutyExcel.getUnitName()))
                        .staffIds(Collections.singletonList(staffUsers.get(0).getId()))
                        .leaderIds(Collections.singletonList(leaderUsers.get(0).getId()))
                        .directorIds(Collections.singletonList(directorUsers.get(0).getId()))
                        .build();
                dutyService.saveDuty(duty);
            }

            int successNum = dutyExcelList.size() - deptList.size();
            StringBuilder result = new StringBuilder("成功保存 " + successNum + " 条数据 \n");
            if (!deptList.isEmpty()) {
                result.append(String.join(",", deptList)).append("部门数据保存失败 \n");
                result.append(String.join(",", userList)).append("人员不存在");
            }
            return R.success(result);
        } catch (Exception e) {
            throw new ServiceException("导入失败：\n" + e.getMessage());
        }
    }
}
